﻿$.widget("socaloud.leaguesWidget", {

    options: {
        template: 'templates/leagues-template.html',
        ticker: $.connection.leaguesTicker
    },

    _create: function () {
        var self = this;

        var content = Extension.getTemplate(self.options.template);
        self.element.append(content);

        self.options.viewModel = {
            leagues: ko.observableArray([]),
            inProgress: function (time) {
                return time !== 'Finished' && time !== 'Not started';
            },
            matchDetailsUrl: function (id) {
                return baseUrl + 'Home/Match/' + id;
            }
        };

        ko.applyBindings(self.options.viewModel, self.element[0]);

        //Repository.Soccer.getLeaguesAndMatches(function (data) {
        //    self.options.viewModel.leagues(data || []);
        //});

        function init() {
            return self.options.ticker.server.getLeagues().done(function (leagues) {
                if (!!leagues) {
                    self.options.viewModel.leagues(leagues || []);
                }
            });
        }

        $.extend(self.options.ticker.client, {
            updateLeagues: function (leagues) {
                if (!!leagues) {
                    console.log(leagues);
                    self.options.viewModel.leagues(leagues || []);
                }
            }
        });

        $.connection.hub.start()
            .pipe(init)
            .done(function (state) {
                console.log('done');
            });
        
    },

    _destroy: function () {
        $.connection.hub.stop();
        alert('destory leagues');
        this.element.html('');
    }
});